<route lang="json5" type="page">
{
  style: { navigationBarTitleText: '登录' },
}
</route>

<template>
  <view class="login">
    <view class="logo">
      <image
        class="logo-img"
        src="@/static/logo.png"
      ></image>
      <view class="welcome">临海市农村文化礼堂</view>
    </view>
    <view class="input-wrap">
      <wd-form
        ref="formRef"
        :model="formModel"
      >
        <wd-cell-group border>
          <wd-input
            label="用户名"
            label-width="160rpx"
            prop="username"
            size="large"
            v-model="formModel.username"
            placeholder="请输入用户名"
            :rules="[{ required: true, message: '请填写用户名' }]"
          />
          <wd-input
            label="密码"
            label-width="160rpx"
            prop="password"
            show-password
            size="large"
            v-model="formModel.password"
            placeholder="请输入密码"
            :rules="[{ required: true, message: '请填写密码' }]"
          />
          <!-- <wd-input
            custom-class="captcha-input"
            v-show="captchaImg"
            label="验证码"
            label-width="160rpx"
            prop="captcha"
            size="large"
            v-model="formModel.captcha"
            placeholder="请输入验证码"
            :rules="[{ required: true, message: '请填写验证码' }]"
          >
            <template #suffix>
              <image class="captcha-img" :src="captchaImg" @click="changeCaptcha" />
            </template>
</wd-input> -->
        </wd-cell-group>
      </wd-form>
    </view>
    <wd-button
      type="primary"
      block
      @click="handleLogin"
    >
      登录
    </wd-button>
    <!-- <user-protocol v-model:checked="userProtocolChecked"></user-protocol> -->
  </view>
</template>

<script setup>
import LoginApi from '@/service/login'
import { useUserStore } from '@/store'
import { useDictStore } from '@/store/dict'
import { currRoute } from '@/utils'
import { usePermissionStore } from '@/store/permission'

const formRef = ref(null)
const formModel = reactive({
  username: '',
  password: '',
  captcha: '',
  checkKey: '',
})

const captchaImg = ref('')

const getCaptchaImg = async () => {
  const key = new Date().getTime()
  formModel.checkKey = key
  const { result } = await LoginApi.getCaptchaImg(key)
  if (result) {
    captchaImg.value = result.replace(/[\r\n]/g, '')
    console.log(captchaImg.value)
  }
}
// getCaptchaImg()

const changeCaptcha = () => {
  getCaptchaImg()
}

const { setMenuList, setActionList } = usePermissionStore()
const getPermission = async () => {
  const { code, result, message } = await LoginApi.getUserPermission()
  if (code === 0 && result) {
    setMenuList(result.menu)
    setActionList(result.codeList)
    return true
  }
  uni.showToast({
    icon: 'error',
    title: message,
  })
  return false
}

const handleLogin = () => {
  formRef.value
    .validate()
    .then(async (valid) => {
      if (valid) {
        const { code, message, result } = await LoginApi.login(formModel)
        console.log('data', result)
        if (code === 200 && result) {
          const { token, userInfo, sysAllDictItems, departs } = result
          useUserStore().setUserInfo({ ...userInfo, token, departs })
          useDictStore().setDictData({ ...sysAllDictItems })
          const permissionResult = await getPermission()
          if (permissionResult) {
            uni.showToast({
              icon: 'success',
              title: '登录成功',
            })
            setTimeout(() => {
              const { query } = currRoute()
              console.log('currRoute()', currRoute())
              if (query) {
                uni.redirectTo({ url: query })
              } else {
                uni.switchTab({ url: '/pages/index/index' })
              }
            }, 1000)
          }
        } else {
          // getCaptchaImg()
          uni.showToast({
            icon: 'none',
            title: message,
          })
        }
      }
    })
    .catch(() => {
      // 处理验证错误
      console.warn('校验失败')
    })
}
</script>

<style lang="scss" scoped>
.login {
  padding: 40rpx;

  .logo {
    margin: 0 auto;
    margin: 160rpx 0 80rpx;

    &-img {
      display: block;
      width: 280rpx;
      height: 280rpx;
      margin: 0 auto;
      background: $uni-bg-color-grey;
    }

    .welcome {
      height: 70rpx;
      padding-top: 10rpx;
      font-size: 44rpx;
      font-weight: bold;
      line-height: 70rpx;
      color: $uni-text-color;
      text-align: center;
    }
  }

  .input-wrap {
    width: 100%;
    padding-bottom: $uni-spacing-col-lg;
  }

  :deep() .wd-input {
    display: flex !important;
    align-items: center !important;
    height: 80rpx;

    /* stylelint-disable-next-line selector-class-pattern */
    .wd-input__error-message {
      position: absolute;
    }
  }

  .captcha-img {
    width: 150rpx;
    height: 80rpx;
  }
}
</style>
